package com.dandelion.common.service;

import com.dandelion.common.dao.auto.mapper.ThirdUserBindMapper;
import com.dandelion.common.dao.auto.pojo.ThirdUserBind;
import com.dandelion.common.dao.auto.pojo.ThirdUserBindCriteria;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ThirdUserBindService {
    private static final Logger logger = LoggerFactory.getLogger(ThirdUserBindService.class);

    @Autowired
    private ThirdUserBindMapper thirdUserBindMapper;

    public ThirdUserBind selectByOpenid(String openid, String platform) {
        ThirdUserBindCriteria criteria = new ThirdUserBindCriteria();
        criteria.createCriteria()
                .andOpenidEqualTo(openid)
                .andPlatformEqualTo(platform);
        criteria.setLimit(1);
        List<ThirdUserBind> resultList = thirdUserBindMapper.selectByExample(criteria);
        return CollectionUtils.isEmpty(resultList) ? null : resultList.get(0);
    }

    public ThirdUserBind bindUserAccount(long userId, String platform, String openid, String sessionKey) {
        ThirdUserBind bind = new ThirdUserBind();
        bind.setUserId(userId);
        bind.setOpenid(openid);
        bind.setPlatform(platform);
        bind.setSessionKey(sessionKey);
        bind.setCreateTime(new Date());
        thirdUserBindMapper.insertSelective(bind);
        return bind;
    }

    public void updateBindUserAccount(Long userId, String sessionKey) {
        ThirdUserBindCriteria criteria = new ThirdUserBindCriteria();
        criteria.createCriteria()
                .andUserIdEqualTo(userId);
        ThirdUserBind bind = new ThirdUserBind();
        bind.setSessionKey(sessionKey);

        thirdUserBindMapper.updateByExampleSelective(bind, criteria);
    }
}
